#!/bin/bash

# Copyright (C) 2017 - 2018  Asaf Niv

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Set things up
clear
cd "$(dirname "$0")"
export HOSTS=/etc/hosts
# For Android, you may need to use /system/etc/hosts
export TMP=temp
# If there is no sources list, make one with this dirty hack.
ls sources  > /dev/null || echo "
https://hosts-file.net/ad_servers.txt
https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&mimetype=plaintext&useip=0.0.0.0
https://raw.githubusercontent.com/AdAway/adaway.github.io/master/hosts.txt
https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.2o7Net/hosts
https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Risk/hosts
https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Spam/hosts
https://raw.githubusercontent.com/FadeMind/hosts.extras/master/SpotifyAds/hosts
https://raw.githubusercontent.com/tyzbit/hosts/master/data/tyzbit/hosts
https://raw.githubusercontent.com/WindowsLies/BlockWindows/master/hosts
https://hosts-file.net/download/hosts.txt
https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts
" >> sources
# Add my hosts to the list
ls myhosts > /dev/null || echo "
0.0.0.0 incoming.telemetry.mozilla.org
0.0.0.0 telemetry.mozilla.org
0.0.0.0 telemetry-experiment.cdn.mozilla.net
" >> myhosts
# Make sure that there are no duplicate sources
sort -u sources --output=sources || :
# Warm up
mkdir $TMP || : && rm -rf $TMP/* || : && cd $TMP
# Download lists
wget -i ../sources
cat * >> /tmp/trackers && rm -rf * && cd ..
# Kill localhost timeout
sed -i s/127.0.0.1/0.0.0.0/g /tmp/trackers || :
# Remove duplicate lines
sort -u /tmp/trackers --output=/tmp/trackers || :
# Whitelist
awk 'FNR==NR {hash[$0]; next} !($0 in hash)' whitelist /tmp/trackers > /tmp/trackers || :
# Do the thing this script is supposed to do.
cat myhosts >> $HOSTS
cat /tmp/trackers >> $HOSTS
# Clean up
rm -f /tmp/trackers
rm -rf temp/
sort -u $HOSTS --output=$HOSTS || :
rm -f sources~
rm -f $HOSTS\~
clear
echo "That's it! You are now free of tracking domains!"